/**
 * Description:
 * Class Name:SimpleAIOClient
 * Date:2022/5/26 17:37
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_3_基于TCP协议的网络编程._17_3_8_使用AIO实现非阻塞通信;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.Charset;

public class SimpleAIOClient {
    static final int PORT = 30000;

    public static void main(String[] args) throws Exception {
        // 用于读取数据的ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        Charset utf = Charset.forName("utf-8");
        try (
                // ①创建AsynchronousSocketChannel对象
                AsynchronousSocketChannel clientChannel = AsynchronousSocketChannel.open()
                ){
            // ②连接远程服务器
            clientChannel.connect(new InetSocketAddress("localhost", 30000)).get();     // ④
            buffer.clear();
            // ③从clientChannel中读取数据
            clientChannel.read(buffer).get();                                                         // ⑤
            buffer.flip();
            // 将buffer中的内容转换成字符串
            String content = utf.decode(buffer).toString();
            System.out.println("服务器信息为：" + content);
        }
    }
}
